package net.yw365.wxapkg;

import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * Created by on 2018/6/6.
 * 微信小程序包解压
 *
 * @author 席有芳
 */
public class WxPkgInputStream {

    /**
     * in 流
     */
    private DataInputStream in;

    /**
     * 文件文件
     */
    private WxFile wxFile;

    /**
     * 当前文件
     */
    private WxFile currentWxFile;

    /**
     * 文件数量
     */
    private int count;

    /**
     * 构造函数
     *
     * @param in 流
     */
    public WxPkgInputStream(InputStream in) throws IOException {
        this.in = new DataInputStream(in);
        decodeWxFile(this.in);
    }

    /**
     * 解码文件名区域
     *
     * @param in in
     */
    private void decodeWxFile(DataInputStream in) throws IOException {
        in.readByte();  //标识
        in.readInt();   //未知
        in.readInt();   //文件名域长度
        in.readInt();   //内容域长度
        in.readByte();  //未知
        count = in.readInt();   //文件数量
        if (count > 0) {
            WxFile nextWxFile = null;
            for (int i = 0; i < count; i++) {
                byte[] name = new byte[in.readInt()];                //文件名长度
                int j = in.read(name);
                int offset = in.readInt();                           //偏移
                int length = in.readInt();                           //内容长度
                WxFile currentWxFile = new WxFile();
                currentWxFile.setName(new String(name, "UTF-8"));
                currentWxFile.setOffset(offset);
                currentWxFile.setLength(length);
                if (nextWxFile == null) {
                    nextWxFile = currentWxFile;
                    wxFile = nextWxFile;
                } else {
                    nextWxFile.setNext(currentWxFile);
                    nextWxFile = currentWxFile;
                }
            }
        }
        currentWxFile = wxFile;                                     //当前处理的文件
    }

    /**
     * @param out 输出流
     */
    public void readWxFile(OutputStream out) throws IOException {
        if (currentWxFile == null) {
            throw new IOException("no more files");
        }
        int length = currentWxFile.getLength();
        byte[] buffer = new byte[length];
        int readSize;
        while (length > 0 && (readSize = in.read(buffer)) != -1) {
            length -= readSize;
            out.write(buffer, 0, readSize);
        }
        currentWxFile = currentWxFile.getNext();
    }

    /**
     * 读取文件
     *
     * @return WxFile
     */
    public WxFile getNextWxFile() {
        return currentWxFile;
    }

    /**
     * 获取文件数量
     * @return
     *  count
     */
    public int getCount() {
        return count;
    }

    /**
     * 关闭流
     *
     * @throws IOException IO异常
     */
    public void close() throws IOException {
        if (in != null)
            in.close();
    }

}
